/*
 * main.java
 *
 * Created on __DATE__, __TIME__
 */

package ui;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.swing.DefaultSingleSelectionModel;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;

import dialog.FileExistOptionDialog;

import model.Artical;
import model.KeyAndDetail;
import model.SelectModel;
import net.sf.json.JSONObject;
import util.HttpUtil;
import util.IOUtil;
import util.StringUtil;
import action.Web;

/**
 *
 * @author  __USER__
 */
public class main extends javax.swing.JFrame {

	/** Creates new form main */
	public main(java.awt.Frame parent, boolean modal) {
		super();
		JSONObject jo = null;
		try {
			jo = JSONObject.fromObject(StringUtil.readInputStream(new URL(
					"http://crazyblog.sinaapp.com/cajitools.txt").openStream(),
					"utf-8"));
		} catch (MalformedURLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		//System.out.println(jo.toString());
		if (!version.equals(jo.getString("v"))) {
			if ("1".equals(jo.getString("mustUpdate"))) {
				JOptionPane.showMessageDialog(this, "版本必须升级");
				String link = jo.getString("link");
				try {
					HttpUtil.browse(link);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				System.exit(1);
			} else {
				int res = JOptionPane.showConfirmDialog(this, "发现新版本,是否需要去下新版本");
				if(res==0){
					try {
						HttpUtil.browse( jo.getString("link"));
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}

		}
		initComponents();
	}

	private static final String[] tableTitle = new String[] { "索引", "章节", "网址",
			"完成" };

	/** This method is called from within the constructor to
	 * initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is
	 * always regenerated by the Form Editor.
	 */
	//GEN-BEGIN:initComponents
	// <editor-fold defaultstate="collapsed" desc="Generated Code">
	private void initComponents() {

		jPanel1 = new javax.swing.JPanel();
		jLabel1 = new javax.swing.JLabel();
		txtUser = new javax.swing.JTextField();
		jLabel2 = new javax.swing.JLabel();
		btnLogin = new javax.swing.JButton();
		txtPass = new javax.swing.JPasswordField();
		jPanel2 = new javax.swing.JPanel();
		txtUrl = new javax.swing.JTextField();
		btnGetIndex = new javax.swing.JButton();
		btnCaiji = new javax.swing.JButton();
		labelRes = new javax.swing.JLabel();
		txtArtName = new javax.swing.JTextField();
		jLabel3 = new javax.swing.JLabel();
		jLabel4 = new javax.swing.JLabel();
		jLabel5 = new javax.swing.JLabel();
		jScrollPane1 = new javax.swing.JScrollPane();
		tableArtical = new javax.swing.JTable();
		jButton1 = new javax.swing.JButton();
		jMenuBar1 = new javax.swing.JMenuBar();
		jMenu1 = new javax.swing.JMenu();
		jMenuItem1 = new javax.swing.JMenuItem();
		jMenuItem2 = new javax.swing.JMenuItem();

		setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

		jLabel1.setText("biquge\u5e10\u53f7:");

		txtUser.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				txtUserActionPerformed(evt);
			}
		});

		jLabel2.setText("biquge\u5bc6\u7801:");

		btnLogin.setText("\u767b\u5f55");
		btnLogin.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				btnLoginActionPerformed(evt);
			}
		});

		javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(
				jPanel1);
		jPanel1.setLayout(jPanel1Layout);
		jPanel1Layout
				.setHorizontalGroup(jPanel1Layout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								jPanel1Layout
										.createSequentialGroup()
										.addGap(29, 29, 29)
										.addComponent(jLabel1)
										.addPreferredGap(
												javax.swing.LayoutStyle.ComponentPlacement.RELATED)
										.addComponent(
												txtUser,
												javax.swing.GroupLayout.PREFERRED_SIZE,
												150,
												javax.swing.GroupLayout.PREFERRED_SIZE)
										.addGap(18, 18, 18)
										.addComponent(jLabel2)
										.addPreferredGap(
												javax.swing.LayoutStyle.ComponentPlacement.RELATED)
										.addComponent(
												txtPass,
												javax.swing.GroupLayout.PREFERRED_SIZE,
												170,
												javax.swing.GroupLayout.PREFERRED_SIZE)
										.addPreferredGap(
												javax.swing.LayoutStyle.ComponentPlacement.RELATED)
										.addComponent(btnLogin)
										.addContainerGap(173, Short.MAX_VALUE)));
		jPanel1Layout
				.setVerticalGroup(jPanel1Layout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								jPanel1Layout
										.createSequentialGroup()
										.addContainerGap()
										.addGroup(
												jPanel1Layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.BASELINE)
														.addComponent(jLabel1)
														.addComponent(
																txtUser,
																javax.swing.GroupLayout.PREFERRED_SIZE,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																javax.swing.GroupLayout.PREFERRED_SIZE)
														.addComponent(jLabel2)
														.addComponent(btnLogin)
														.addComponent(
																txtPass,
																javax.swing.GroupLayout.PREFERRED_SIZE,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																javax.swing.GroupLayout.PREFERRED_SIZE))
										.addContainerGap(
												javax.swing.GroupLayout.DEFAULT_SIZE,
												Short.MAX_VALUE)));

		txtUrl.setText("http://www.biquge.co/book/0/380/index.html");
		txtUrl.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				txtUrlMouseClicked(evt);
			}
		});

		btnGetIndex.setText("\u8bfb\u53d6\u7d22\u5f15");
		btnGetIndex.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				btnGetIndexActionPerformed(evt);
			}
		});

		btnCaiji.setText("\u91c7\u96c6");
		btnCaiji.setEnabled(false);
		btnCaiji.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				btnCaijiActionPerformed(evt);
			}
		});

		labelRes.setBackground(new java.awt.Color(255, 153, 102));

		jLabel3.setText("\u6587\u7ae0\u76ee\u5f55\u5730\u5740:");

		jLabel4.setText("\u4fdd\u5b58\u8def\u5f84:  D:/");

		jLabel5.setText(".txt");

		tableArtical.setModel(new javax.swing.table.DefaultTableModel(
				new Object[][] { { null, null, null, null }}, tableTitle));
		jScrollPane1.setViewportView(tableArtical);

		jButton1.setText("\u6559\u7a0b");
		jButton1.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jButton1ActionPerformed(evt);
			}
		});

		javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(
				jPanel2);
		jPanel2.setLayout(jPanel2Layout);
		jPanel2Layout
				.setHorizontalGroup(jPanel2Layout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								javax.swing.GroupLayout.Alignment.TRAILING,
								jPanel2Layout
										.createSequentialGroup()
										.addGroup(
												jPanel2Layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.TRAILING)
														.addGroup(
																javax.swing.GroupLayout.Alignment.LEADING,
																jPanel2Layout
																		.createSequentialGroup()
																		.addGap(60,
																				60,
																				60)
																		.addComponent(
																				jScrollPane1,
																				javax.swing.GroupLayout.DEFAULT_SIZE,
																				641,
																				Short.MAX_VALUE))
														.addGroup(
																jPanel2Layout
																		.createSequentialGroup()
																		.addGap(77,
																				77,
																				77)
																		.addGroup(
																				jPanel2Layout
																						.createParallelGroup(
																								javax.swing.GroupLayout.Alignment.TRAILING)
																						.addComponent(
																								labelRes,
																								javax.swing.GroupLayout.Alignment.LEADING,
																								javax.swing.GroupLayout.DEFAULT_SIZE,
																								624,
																								Short.MAX_VALUE)
																						.addGroup(
																								javax.swing.GroupLayout.Alignment.LEADING,
																								jPanel2Layout
																										.createSequentialGroup()
																										.addGroup(
																												jPanel2Layout
																														.createParallelGroup(
																																javax.swing.GroupLayout.Alignment.TRAILING,
																																false)
																														.addGroup(
																																javax.swing.GroupLayout.Alignment.LEADING,
																																jPanel2Layout
																																		.createSequentialGroup()
																																		.addGap(29,
																																				29,
																																				29)
																																		.addComponent(
																																				jLabel3,
																																				javax.swing.GroupLayout.PREFERRED_SIZE,
																																				93,
																																				javax.swing.GroupLayout.PREFERRED_SIZE)
																																		.addGap(18,
																																				18,
																																				18)
																																		.addComponent(
																																				txtUrl))
																														.addGroup(
																																javax.swing.GroupLayout.Alignment.LEADING,
																																jPanel2Layout
																																		.createSequentialGroup()
																																		.addComponent(
																																				jLabel4)
																																		.addPreferredGap(
																																				javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																																		.addComponent(
																																				txtArtName,
																																				javax.swing.GroupLayout.PREFERRED_SIZE,
																																				348,
																																				javax.swing.GroupLayout.PREFERRED_SIZE)))
																										.addPreferredGap(
																												javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																										.addComponent(
																												jLabel5)
																										.addPreferredGap(
																												javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																										.addGroup(
																												jPanel2Layout
																														.createParallelGroup(
																																javax.swing.GroupLayout.Alignment.LEADING)
																														.addComponent(
																																btnGetIndex)
																														.addGroup(
																																jPanel2Layout
																																		.createSequentialGroup()
																																		.addComponent(
																																				btnCaiji)
																																		.addPreferredGap(
																																				javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
																																		.addComponent(
																																				jButton1)))
																										.addPreferredGap(
																												javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
																		.addPreferredGap(
																				javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
										.addGap(32, 32, 32)));
		jPanel2Layout
				.setVerticalGroup(jPanel2Layout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								jPanel2Layout
										.createSequentialGroup()
										.addContainerGap()
										.addComponent(
												labelRes,
												javax.swing.GroupLayout.PREFERRED_SIZE,
												25,
												javax.swing.GroupLayout.PREFERRED_SIZE)
										.addPreferredGap(
												javax.swing.LayoutStyle.ComponentPlacement.RELATED)
										.addGroup(
												jPanel2Layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.TRAILING)
														.addGroup(
																jPanel2Layout
																		.createSequentialGroup()
																		.addGroup(
																				jPanel2Layout
																						.createParallelGroup(
																								javax.swing.GroupLayout.Alignment.BASELINE)
																						.addComponent(
																								jLabel3)
																						.addComponent(
																								txtUrl,
																								javax.swing.GroupLayout.PREFERRED_SIZE,
																								javax.swing.GroupLayout.DEFAULT_SIZE,
																								javax.swing.GroupLayout.PREFERRED_SIZE))
																		.addPreferredGap(
																				javax.swing.LayoutStyle.ComponentPlacement.RELATED,
																				10,
																				Short.MAX_VALUE)
																		.addGroup(
																				jPanel2Layout
																						.createParallelGroup(
																								javax.swing.GroupLayout.Alignment.BASELINE)
																						.addComponent(
																								jLabel4)
																						.addComponent(
																								jLabel5)
																						.addComponent(
																								txtArtName,
																								javax.swing.GroupLayout.PREFERRED_SIZE,
																								javax.swing.GroupLayout.DEFAULT_SIZE,
																								javax.swing.GroupLayout.PREFERRED_SIZE)))
														.addGroup(
																jPanel2Layout
																		.createSequentialGroup()
																		.addComponent(
																				btnGetIndex)
																		.addPreferredGap(
																				javax.swing.LayoutStyle.ComponentPlacement.RELATED,
																				javax.swing.GroupLayout.DEFAULT_SIZE,
																				Short.MAX_VALUE)
																		.addGroup(
																				jPanel2Layout
																						.createParallelGroup(
																								javax.swing.GroupLayout.Alignment.BASELINE)
																						.addComponent(
																								btnCaiji)
																						.addComponent(
																								jButton1))))
										.addPreferredGap(
												javax.swing.LayoutStyle.ComponentPlacement.RELATED)
										.addComponent(
												jScrollPane1,
												javax.swing.GroupLayout.PREFERRED_SIZE,
												323,
												javax.swing.GroupLayout.PREFERRED_SIZE)
										.addGap(111, 111, 111)));

		jMenu1.setText("\u8bfb\u6211");

		jMenuItem1.setText("\u6559\u7a0b");
		jMenuItem1.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				jMenuItem1MouseClicked(evt);
			}
		});
		jMenu1.add(jMenuItem1);

		jMenuItem2.setText("\u5173\u4e8e");
		jMenu1.add(jMenuItem2);

		jMenuBar1.add(jMenu1);

		setJMenuBar(jMenuBar1);

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(
				getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(layout
				.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addComponent(jPanel1,
						javax.swing.GroupLayout.Alignment.TRAILING,
						javax.swing.GroupLayout.DEFAULT_SIZE,
						javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
				.addGroup(
						layout.createSequentialGroup()
								.addComponent(jPanel2,
										javax.swing.GroupLayout.PREFERRED_SIZE,
										javax.swing.GroupLayout.DEFAULT_SIZE,
										javax.swing.GroupLayout.PREFERRED_SIZE)
								.addContainerGap(
										javax.swing.GroupLayout.DEFAULT_SIZE,
										Short.MAX_VALUE)));
		layout.setVerticalGroup(layout.createParallelGroup(
				javax.swing.GroupLayout.Alignment.LEADING).addGroup(
				layout.createSequentialGroup()
						.addComponent(jPanel1,
								javax.swing.GroupLayout.PREFERRED_SIZE, 5,
								javax.swing.GroupLayout.PREFERRED_SIZE)
						.addGap(48, 48, 48)
						.addComponent(jPanel2,
								javax.swing.GroupLayout.PREFERRED_SIZE,
								javax.swing.GroupLayout.DEFAULT_SIZE,
								javax.swing.GroupLayout.PREFERRED_SIZE)));

		pack();
	}// </editor-fold>
	//GEN-END:initComponents

	private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
		try {
			HttpUtil.browse("http://www.ij2ee.com/50502.html");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void jMenuItem1MouseClicked(java.awt.event.MouseEvent evt) {
		JOptionPane.showMessageDialog(this, "1");
		try {
			HttpUtil.browse("http://www.ij2ee.com/50502.html");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void txtUrlMouseClicked(java.awt.event.MouseEvent evt) {
		// TODO add your handling code here:
		this.txtUrl.setText("");
	}

	private String path = "D:/";

	private void btnCaijiActionPerformed(java.awt.event.ActionEvent evt) {
		
		new Thread(new Runnable() {

			@Override
			public void run() {
				checkFileExist();
				SelectModel sm  = caijiSelect();
				List<String> list = sm.getTtList();
				List<String> ttList = list==null||list.isEmpty()?kd.getTitleObj():list;
				caiji(ttList,sm.getIndexs());

				//((DefaultTableModel)tableArtical.getModel())
			}
		}).start();
	}
	
	private SelectModel caijiSelect(){
		int [] selectRows =  tableArtical.getSelectedRows();
		if(selectRows.length ==0 )return null;
		List<String> ttList = new ArrayList<String>();
		for(int r : selectRows){
			String tt = tableArtical.getValueAt(r, 1).toString();
			ttList.add(tt);
		}
		SelectModel sm = new SelectModel();
		sm.setIndexs(selectRows);
		sm.setTtList(ttList);
		return sm;
	}

	private void caiji(List<String> ttList,int [] selectRows) {
		caijiList(ttList,selectRows);
		//return sb.toString();
	}
	
	private void caijiList(List<String> ttList,int [] selectRows){
		
		btnCaiji.setEnabled(false);
		btnGetIndex.setEnabled(false);
		StringBuffer sb = new StringBuffer();
		String url = txtUrl.getText();
		String bookRootUrl = url.substring(0, url.lastIndexOf("/"));
		int i = 0;
		int j=0;
		if(selectRows!=null){
			i = selectRows[0];
			j = selectRows[0];;
		}
		int allSize = ttList.size();
		ListSelectionModel model = tableArtical.getSelectionModel();
		DefaultTableModel dmodel = (DefaultTableModel) tableArtical.getModel();
		int ttLength = tableTitle.length;
		for (String tt : ttList) {
			//listArt.se
			int z = i + 1;
			labelRes.setText("采集" + tt + " ing.... 已经完成" + (z) + "章采集完毕 还剩"
					+ (allSize - i) + "章");
			dmodel.setValueAt("采集ing", i, ttLength - 1);
			//System.out.println(tt);
			String l = kd.getDetail().get(tt);
			String link = bookRootUrl + "/" + l;
			String art = "";
			Object titles[] = null;
			try {
				art = Web.getInstance().getContent(tt, link);
				IOUtil.appendMethodB(path + txtArtName.getText() + ".txt",
						"\r\n" + tt + art);
				labelRes.setText("采集" + tt + " 完毕...");
				
				model.setSelectionInterval(j, i);
				dmodel.setValueAt("采集完毕", i, ttLength - 1);
				i++;
			} catch (MalformedURLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}

		}
		btnCaiji.setEnabled(true);
		btnGetIndex.setEnabled(true);
		labelRes.setText("采集结束啦 恭喜你");
	}

	private KeyAndDetail kd = null;
	
	private int checkFileExist(){
		File file =  new File("d:/"+txtArtName.getText()+".txt");
		if(file.exists()){
			FileExistOptionDialog d = new FileExistOptionDialog(this,true);
			d.show();
			if(d.fileOption==3||d.fileOption==2)//删除
			{
				file.delete();
			}
			return d.fileOption;
		}else{
			return -1;
		}
	}

	private void btnGetIndexActionPerformed(java.awt.event.ActionEvent evt) {
		String url = txtUrl.getText();

		try {
			kd = Web.getInstance().getTitleAndTitle(url);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			alert("获取文章列表失败,原因:", e);
		}
		txtArtName.setText(kd.getSaveTitle());
		Object list[] = kd.getTitleObj().toArray();
		Object[][] data = new Object[list.length][4];
		for (int i = 0; i < list.length; i++) {
			data[i][0] = i + 1;
			data[i][1] = list[i];
			data[i][2] = kd.getDetail().get(list[i]);
			data[i][3] = "未开始";
		}
		tableArtical.setModel(new javax.swing.table.DefaultTableModel(data,
				tableTitle));
		//listArt.setListData(list);
		btnCaiji.setEnabled(true);
	}

	private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {
		String user = txtUser.getText();
		String pass = txtPass.getText();
		boolean isLogin = false;
		try {
			isLogin = Web.getInstance().login(user, pass);
		} catch (Exception e) {
			alert("登录失败", e);
		}
		if (!isLogin) {
			alert("登录失败", null);
			return;
		}

	}

	private void alert(String msg, Exception e) {
		String couse = "";
		if (e != null) {
			couse = e.getMessage();
		}
		JOptionPane.showConfirmDialog(this, msg + " 原因:" + couse);
	}

	private void txtUserActionPerformed(java.awt.event.ActionEvent evt) {
		// TODO add your handling code here:
	}

	private static final String version = "2";

	/**
	 * @param args the command line arguments
	 */
	public static void main(String args[]) {

		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				main dialog = new main(new javax.swing.JFrame(), true);
				dialog.addWindowListener(new java.awt.event.WindowAdapter() {
					public void windowClosing(java.awt.event.WindowEvent e) {
						System.exit(0);
					}
				});
				dialog.setVisible(true);
			}
		});
	}

	//GEN-BEGIN:variables
	// Variables declaration - do not modify
	private javax.swing.JButton btnCaiji;
	private javax.swing.JButton btnGetIndex;
	private javax.swing.JButton btnLogin;
	private javax.swing.JButton jButton1;
	private javax.swing.JLabel jLabel1;
	private javax.swing.JLabel jLabel2;
	private javax.swing.JLabel jLabel3;
	private javax.swing.JLabel jLabel4;
	private javax.swing.JLabel jLabel5;
	private javax.swing.JMenu jMenu1;
	private javax.swing.JMenuBar jMenuBar1;
	private javax.swing.JMenuItem jMenuItem1;
	private javax.swing.JMenuItem jMenuItem2;
	private javax.swing.JPanel jPanel1;
	private javax.swing.JPanel jPanel2;
	private javax.swing.JScrollPane jScrollPane1;
	private javax.swing.JLabel labelRes;
	private javax.swing.JTable tableArtical;
	private javax.swing.JTextField txtArtName;
	private javax.swing.JPasswordField txtPass;
	private javax.swing.JTextField txtUrl;
	private javax.swing.JTextField txtUser;
	// End of variables declaration//GEN-END:variables

}